using System; 
using System.Collections.Generic;
using System.IO; 
using UnityEditor;
using UnityEngine;

public class BuildAllAssetBundlesEditor
{
    /// <summary>
    /// 0:标记 1：自己统计
    /// </summary>
    private static int abType = 1;

    [MenuItem("cwl/AssetBundle/Core/编辑器自定义")]
    static void BuildAllAssetBundles() //依赖打包
    {
        //资源路径 shortPath：      Assets/AssetBundlePackage/Config/UdpReceiveAdressIP.txt  
        //打包文件路径 fileName：   AssetBundlePackage/Config/UdpReceiveAdressIP  
        //打包文件后缀 variant：    场景：unity  其他：assetBundle

        //打包存储路径 根节点
        string newToPath = Application.dataPath + "/../AssetBundlePackage/Windows/"; //打包存储路径

        if (!Directory.Exists(newToPath))
            Directory.CreateDirectory(newToPath);

        AssetBundleManifest manifest = null;
        BuildTarget buildTarget = EditorUserBuildSettings.activeBuildTarget;
        BuildAssetBundleOptions options = BuildAssetBundleOptions.ChunkBasedCompression;


        //abType == 0;
        manifest = BuildPipeline.BuildAssetBundles(newToPath, options, buildTarget);

        //// abType==1;
        // AssetBundleBuild[] builds = null;
        // manifest = BuildPipeline.BuildAssetBundles(newToPath, builds, options, buildTarget);
    }

    [MenuItem("cwl/AssetBundle/标记打包 activeBuildTarget")]
    static void BuildAllAssetBundles1() //依赖打包
    {
        // BuildAB(BuildTarget.Android, 0);
        BuildAB(EditorUserBuildSettings.activeBuildTarget, 0);
    }

    [MenuItem("cwl/AssetBundle/统计打包 activeBuildTarget")]
    static void BuildAllAssetBundles2() //依赖打包
    {
        // BuildAB(BuildTarget.Android, 1);
        BuildAB(EditorUserBuildSettings.activeBuildTarget, 1);
    }


    #region 打包

    static void BuildAB(BuildTarget buildTarget, int _abtype)
    {
        abType = _abtype;
        BuildAB(buildTarget);
    }

    static void BuildAB(BuildTarget buildTarget)
    {
        //打包存储路径 根节点
        string newToPath = Application.dataPath + $"/../AssetBundlePackage/{buildTarget}/"; //打包存储路径 
        if (!Directory.Exists(newToPath))
            Directory.CreateDirectory(newToPath);

        SwitchBuildTarget(buildTarget); //切换平台
        BuildAssetBundleOptions options = BuildAssetBundleOptions.ChunkBasedCompression;

        DateTime startTime = DateTime.Now;
        AssetBundleManifest manifest = null;
        if (abType == 0)
        {
            BuildAllAssetBundlesImporter();
            manifest = BuildPipeline.BuildAssetBundles(newToPath, options, buildTarget);
        }
        else
        {
            BuildAllAssetBundlesImporter();
            AssetBundleBuild[] builds = GetAddAssetBundle().ToArray(); // Assets/AssetBundlePackage/Config/UdpReceiveAdressIP.AB
            manifest = BuildPipeline.BuildAssetBundles(newToPath, builds, options, buildTarget);
        }

        if (manifest)
        {
            DateTime endTime = DateTime.Now;
            TimeSpan useTime = endTime - startTime;
            Debug.Log($"abover:{useTime}");
        }
    }

    static void SwitchBuildTarget(BuildTarget buildTarget)
    {
        BuildTargetGroup buildTargetGroup = GetBuildTargetGroup(buildTarget);
        if (buildTarget != EditorUserBuildSettings.activeBuildTarget)
        {
            Debug.LogFormat("Switch BuildTarget  {0} => {1}", EditorUserBuildSettings.activeBuildTarget, buildTarget);
            EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildTarget);
        }
    }

    static BuildTargetGroup GetBuildTargetGroup(BuildTarget buildTarget)
    {
        switch (buildTarget)
        {
            case BuildTarget.iOS:
                return BuildTargetGroup.iOS;
            case BuildTarget.StandaloneOSX:
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:
            case BuildTarget.StandaloneLinux64:
                return BuildTargetGroup.Standalone;
            case BuildTarget.Android:
                return BuildTargetGroup.Android;
        }

        return BuildTargetGroup.Unknown;
    }

    #endregion

    #region MyRegion 标记

    [MenuItem("cwl/AssetBundle/标记 统计")]
    static void BuildAllAssetBundlesImporter()
    {
        Clear();
        AssetDatabase.RemoveUnusedAssetBundleNames();

        string[] folderroot = { "Art", "CommonArt" };
        string[] folderab = { "Scene", "Shader", "AB_Anim", "AB_Audio", "AB_Font", "AB_Mat", "AB_Model", "AB_Prefab", "AB_Sprite", "AB_Video" };

        int len = folderroot.Length;
        for (int i = 0; i < len; i++)
        {
            GetFile(Application.dataPath + "/" + folderroot[i]);
        }
    }

    static void GetFile(string path)
    {
        string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
        string file, newPath, newDir;

        for (int i = 0; i < files.Length; i++)
        {
            file = files[i];
            SetABAssetImporter(file);
        }
    }

    private static void SetABAssetImporter(string fullPath)
    {
        if (fullPath.EndsWith(".meta")) return;
        string assetPath = fullPath.Replace(@"\", "/");

        int assetIndex = assetPath.IndexOf("Assets");
        assetPath = assetPath.Substring(assetIndex);

        string assetBundleName = assetPath.ToLower();
        string[] arr = assetPath.Split("/");

        if (arr.Length < 4) return;

        //Assets\Art\Common\AB_Model\NewMaterial1.mat
        assetBundleName = $"{arr[0]}/{arr[1]}/{arr[2]}/{arr[3]}";

        AssetImporter assetImporter = AssetImporter.GetAtPath(assetPath); // GetAtPath方法是获取Assets文件和之后的目录
        if (abType == 0)
        {
            //标记 
            assetImporter.assetBundleName = assetBundleName;
            assetImporter.assetBundleVariant = "ab";
        }
        else
        {
            if (!string.IsNullOrEmpty(assetImporter.assetBundleName))
                assetImporter.assetBundleName = "";
            if (!string.IsNullOrEmpty(assetImporter.assetBundleVariant))
                assetImporter.assetBundleVariant = "";
            AddAssetBundleBuild(assetBundleName, assetPath);
        }
    }

    #endregion

    #region 统计

    private static Dictionary<string, List<string>> assetBundleBuildDic = new Dictionary<string, List<string>>();

    private static void Clear()
    {
        assetBundleBuildDic.Clear();
    }

    private static void AddAssetBundleBuild(string key, string value)
    {
        if (!assetBundleBuildDic.ContainsKey(key))
        {
            assetBundleBuildDic.Add(key, new List<string>());
        }

        if (!assetBundleBuildDic[key].Contains(value))
        {
            assetBundleBuildDic[key].Add(value);
        }
    }


    private static List<AssetBundleBuild> GetAddAssetBundle()
    {
        List<AssetBundleBuild> assetBundleBuildList = new List<AssetBundleBuild>();
        foreach (var item in assetBundleBuildDic)
        {
            AssetBundleBuild build = new AssetBundleBuild();
            build.assetBundleName = item.Key;
            build.assetNames = item.Value.ToArray();
            build.assetBundleVariant = ".ab";
            assetBundleBuildList.Add(build);
        }

        return assetBundleBuildList;
    }

    #endregion
}